package heima_bixiangdong.test.review4;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @DESCRIPTION:
 * @USER: shg
 * @DATE: 2022/11/26 15:00
 */
public class SingleProducerAndConsumerDemo {
    public static void main(String[] args) {
        // 创建生产和消费所需的资源
        Resource resource = new Resource();

        // 创建生产任务和消费任务
        Producer producer = new Producer(resource);
        Consumer consumer = new Consumer(resource);

        // 开启一个生产线程
        new Thread(producer::produceBread).start();
        // 开启一个消费线程
        new Thread(consumer::eatBread).start();
    }
}

// 资源对象
class Resource{
    private String name;
    private int count=1;

    // 标记位
    private boolean flag = false;

    public synchronized void setName(String name){
        if(flag){   // 如果标记为真，则说明盘子里面已经有面包了，生产者等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        this.name = name+count;
        count++;
        System.out.println(Thread.currentThread().getName()+"...生产者..."+this.name);
        // 生产者生产完面包之后，就把标记改为真，并唤醒消费者进行消费
        flag = true;
        this.notify();
    }

    public synchronized void out(){
        if(!flag){  // 如果标记为假，则说明盘子里面没有面包，消费者等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        // 如果标记为真，则说明盘子里有面包，消费者进行消费
        System.out.println(Thread.currentThread().getName()+"...消费者..."+this.name);
        // 消费完后，把标记改为假，并唤醒生产者进行生产
        flag = false;
        this.notify();
    }
}

// 生产任务对象
@Data
@AllArgsConstructor
@NoArgsConstructor
class Producer{

    private Resource resource;
    public void produceBread() {
        while (true){
            resource.setName("面包");
        }
    }
}

// 消费任务对象
@Data
@AllArgsConstructor
@NoArgsConstructor
class Consumer{
    private Resource resource;

    public void eatBread() {
        while (true){
            resource.out();
        }
    }
}
